package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.BaseContext;
import com.example.common.CustomException;
import com.example.constant.BasePage;
import com.example.dto.OrdersDto;
import com.example.entity.*;
import com.example.mapper.OrdersMapper;
import com.example.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Resource
    @Lazy
    private IShoppingCartService shoppingCartService;

    @Resource
    @Lazy
    private IUserService userService;

    @Resource
    @Lazy
    private IAddressBookService addressBookService;

    @Resource
    @Lazy
    private IOrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param order 订单
     * @return 下单结果
     */
    @Override
    @Transactional
    public boolean submit(Orders order) {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();

        // 查询当前用户购物车的数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.getByUserId(userId);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空,不能下单");
        }

        // 查询用户数据
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("用户数据异常");
        }

        //查询地址数据
        Long addressBookId = order.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }

        // 完善订单信息
        long orderId = IdWorker.getId();
        //计算购物车总金额
        AtomicInteger amount = new AtomicInteger(0);
        //计算总金额顺带计算订单明细
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        order.setAmount(new BigDecimal(amount.get()));

        order.setNumber(String.valueOf(orderId));
        order.setId(orderId);
        order.setOrderTime(LocalDateTime.now());

        // 由于个人用户不能完成支付过程，支付时间和订单生成时间一样
        order.setCheckoutTime(LocalDateTime.now());
        // 由于个人用户不能完成支付过程，直接默认为派送中
        order.setStatus(2);

        // 订单里面的用户信息
        order.setUserId(userId);
        order.setUserName((user.getName() == null ? "" : user.getName()));

        // 订单的地址信息
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        order.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) + (addressBook.getCityName() == null ? "" : addressBook.getCityName()) + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        // 向订单表插入数据
        this.save(order);

        // 保存订单明细
        orderDetailService.saveBatch(orderDetails);

        // 清空购物车
        return shoppingCartService.clean();
    }

    /**
     * * 用户的订单分页查询
     *
     * @param basePage 翻页数据
     * @return 翻页对象
     */
    @Override
    public Page<OrdersDto> pageWithOrderDetailAndUser(BasePage basePage) {
        Page<Orders> ordersPage = new Page<>(basePage.getPage(), basePage.getPageSize());

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> page = this.page(ordersPage, wrapper);
        return this.ordersDtoPage(page);
    }


    /**
     * 员工查询订单
     *
     * @param page  翻页数据
     * @param order 订单时间
     * @param begin 开始时间
     * @param end   结束时间
     * @return 翻页对象
     */
    @Override
    public Page<OrdersDto> pageWithOrderDetail(BasePage page, Orders order, LocalDateTime begin, LocalDateTime end) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        // 排序条件
        wrapper.orderByDesc(Orders::getOrderTime);
        // 加入条件查询，订单号
        wrapper.like(order.getNumber() != null, Orders::getNumber, order.getNumber());
        // 订单生成时间大于开始时间
        wrapper.gt(begin != null, Orders::getOrderTime, begin);
        wrapper.lt(end != null, Orders::getOrderTime, end);

        //加入查询条件
        Page<Orders> ordersPage = this.page(new Page<>(page.getPage(), page.getPageSize()),wrapper);

        return this.ordersDtoPage(ordersPage);
    }

    /**
     * 更新订单状态
     *
     * @param order 修改的订单
     * @return 结果
     */
    @Override
    public boolean updateByStatus(Orders order) {
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        // 查询条件
        wrapper.eq(Orders::getId, order.getId());
        // 更新状态
        wrapper.set(order.getStatus() != null, Orders::getStatus, order.getStatus());

        return this.update(wrapper);
    }

    /**
     * 再来一单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public boolean again(Orders order) {
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(order.getId());
        return shoppingCartService.saveWithOrderDetail(orderDetailList);
    }

    /**
     * 分页查询
     *
     * @param page 订单翻页对象
     * @return dto翻页对象
     */
    private Page<OrdersDto> ordersDtoPage(Page<Orders> page) {
        PageDTO<OrdersDto> dtoPageDTO = new PageDTO<>();
        // 拷贝
        BeanUtils.copyProperties(page, dtoPageDTO, "records");
        List<Orders> records = page.getRecords();
        List<OrdersDto> dtoRecords = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            // 拷贝对象
            BeanUtils.copyProperties(item, ordersDto);
            // 用户名
            String userName = item.getUserName();

            if (!StringUtils.isNotEmpty(userName)) {
                String name = userService.getById(item.getUserId()).getName();
                userName = StringUtils.isNotEmpty(name) ? name : "匿名";
            }
            ordersDto.setUserName(userName);
            // 订单明细
            Long orderId = item.getId();
            List<OrderDetail> orderDetails = orderDetailService.getByOrderId(orderId);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        dtoPageDTO.setRecords(dtoRecords);
        return dtoPageDTO;
    }
}
